package com.quan.commons.core.exception;

import com.quan.commons.core.bean.R;
import com.quan.commons.core.constant.CommonsConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    /**
     * VO数据校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题：{}", e.getMessage());

        Map<String, Object> errorMap = new HashMap<String, Object>();

        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach( fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return R.error(CommonsConstant.BizErrorEnums.VAILD_EXCEPTION.getCode(), CommonsConstant.BizErrorEnums.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
    }

    /**
     * 数据库中已存在该记录异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e){
        log.error("数据库中已存在该记录：{}", e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    /**
     * 业务异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public R handleBizException(BizException e){
        log.error("业务异常：{}", e.getMessage());
        return R.error(e.getMessage());
    }

    /**
     * 任意异常处理
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("未知异常：{}，异常类型：{}", throwable.getMessage(), throwable.getClass());
        log.error("异常详细信息：{}", throwable);
        return R.error(CommonsConstant.BizErrorEnums.UNKNOW_EXCEPTION.getCode(), CommonsConstant.BizErrorEnums.UNKNOW_EXCEPTION.getMsg());
    }

}
